<?php
/**
 * This file contains the class AuthorisationModel which provides
 * the code requirements for the authorising a user
 *
 * @copyright  2009 A Memory Tree
 * @license    A Memory Tree License
 * @version    $Id:$
 */
/**
 * This class provides the code for authorising a user
 *
 * @copyright  2009 A Memory Tree
 * @license    A Memory Tree License
 * @version    Release: @package_version@
 */
class AuthorisationModel
{
    /**
     * Access to the database methods
     *
     * @var AuthorisationDB
     */
    private $_db;
    /**
     * Create a new instance of this class
     *
     * @return void
     * @param AuthorisationDB $db
     */
    public function __construct($db)
    {
        $this->_db = $db;
    }
    /**
     * Create an authorisation code for a user
     *
     * @return string
     * @param int $userId
     */
    function createAuthCode($userId)
    {
        $db = $this->_db;
        $authCode = crypt((string)$userId);
        $authId = $db->insertAuthCode($authCode);
        $db->setUserAuthId($userId, $authId);
        return $authCode;
    }
    /**
     * Check if the user id is encrypted within the authentication code
     *
     * @return bool
     * @param int $userId
     * @param string $authCode
     */
    function isValidCode($userId, $authCode)
    {
        $db = $this->_db;
        $storedCode = $db->getAuthCode($userId);
        $isValid = $authCode === $storedCode;
        return $isValid;
    }
    /**
     * Check if the authentication time is older than one day
     *
     * @return bool
     * @param int $userId
     * @param int $hours
     */
    function isUnexpiredTime($userId, $hours = 0)
    {
        $db = $this->_db;
        $isUnexpired = FALSE;
        $time = $db->getTime($userId);
        if (!empty($time)) {
            $authTime = strtotime($time);
            $nowTime = strtotime('now');
            if (empty($hours)) {
                $hours = 24;
            }
            $expireTime = $hours * 60 * 60;
            $isUnexpired = $nowTime - $expireTime < $authTime;
        }
        return $isUnexpired;
    }
    /**
     * Check if the user has a valid authentication code
     *
     * The number of hours before the code expires defaults to 24 * 7 = 168 hours
     *
     * @return bool
     * @param int $userId
     * @param string $authCode
     * @param int $hours
     */
    function validate($userId, $authCode, $hours = 168)
    {
        $validCode = $this->isValidCode($userId, $authCode);
        $validTime = $this->isUnexpiredTime($userId, $hours);
        return $validCode && $validTime;
    }
}
?>
